package com.hjx.service.impl;

import com.hjx.response.AjaxResponse;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

/**
 * <p>Title:</p>
 * <p>Description:</p>
 *
 * @author hjx
 * @date 2020/6/19 - 15:14
 */
public class FileUpAndDownloadService {
    public static String fileUpload(String username, MultipartFile multipartFile, String realPath) throws IOException {
        String originalFilename = multipartFile.getOriginalFilename();
//        String realPath = request.getServletContext().getRealPath("/upload");
        File file = new File(realPath);
        if (!file.exists()) {
            file.mkdirs();
        }
        String targetPath = realPath + File.separator + username + "_" + System.currentTimeMillis() + "_" + originalFilename;
        multipartFile.transferTo(new File(targetPath));
        return targetPath;

    }



    /*
     * 根据浏览器的不同进行编码设置，返回编码后的文件名
     */
    public static String getFileName(HttpServletRequest request, String fileName) throws Exception {
        // IE不同版本User-Agent中出现的关键词
        String[] IEBrowserKeyWords = {"MSIE", "Trident", "Edge"};
        // 获取请求头代理信息
        String userAgent = request.getHeader("User-Agent");
        for (String keyWord : IEBrowserKeyWords) {
            if (userAgent.contains(keyWord)) {
                //IE内核浏览器，统一为UTF-8编码显示
                return URLEncoder.encode(fileName, "UTF-8");
            }
        }
        //火狐等其它浏览器
        return new String(fileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
    }
}
